using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using Microsoft.ApplicationBlocks.Data;
using System.Text;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using System.Collections.Generic;

public partial class Admin_Organization : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        bool isAdmin = UsersBL.GetUserAdmin(Session["loginname"].ToString());
        if (!isAdmin)
            Response.Redirect("~/Home.aspx");

        if (!Page.IsPostBack)
            PopulateRootLevel();
        else
        {
            Load_OrgsParentDDL();
            btnDelete.Visible = false;
        }
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    private void PopulateRootLevel()
    {
        List<OrganizationCDE> orgList = OrganizationBL.GetChildOrgs(0);
        PopulateNodes(orgList, tvOrganization.Nodes);
    }

    protected void TVOrganization_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        PopulateSubLevel(e.Node);
    }

    private void PopulateSubLevel(TreeNode parentNode)
    {
        int parentid = Int32.Parse(parentNode.Value);

        List<OrganizationCDE> orgList = OrganizationBL.GetChildOrgs(parentid);
        PopulateNodes(orgList, parentNode.ChildNodes);
    }

    private void PopulateNodes(List<OrganizationCDE> orgList, TreeNodeCollection nodes)
    {
        foreach (OrganizationCDE dr in orgList)
        {
            TreeNode tn = new TreeNode();
            tn.Text =  Microsoft.Security.Application.AntiXss.HtmlEncode(dr.OrgName);

            tn.Value = dr.OrgID.ToString();
            nodes.Add(tn);
            tn.Expanded = true;

            //If node has child nodes, then enable on-demand populating
            tn.PopulateOnDemand = (dr.ChildCount > 0);
        }
    }

    protected void lnkAddOrg_Click(object sender, EventArgs e)
    {
        pnlManageOrg.Visible = true;
        ddlOrgParent.SelectedIndex = -1;
        txtOrgName.Text = null;
        txtOrgID.Text = null;
        lblActionType.Text = "Add Organization";
        if (tvOrganization.SelectedNode != null)
        {
            tvOrganization.SelectedNode.Selected = false;
        }
    }

    protected void CancelClick(object source, EventArgs e)
    {
        pnlManageOrg.Visible = false;
        ddlOrgParent.SelectedIndex = -1;
        txtOrgName.Text = null;
        txtOrgID.Text = null;
        if (tvOrganization.SelectedNode != null)
        {
            tvOrganization.SelectedNode.Selected = false;
        }
    }

    protected void tvOrganization_SelectedNodeChanged(object sender, EventArgs e)
    {
        pnlManageOrg.Visible = true;
        TreeNode tn = tvOrganization.SelectedNode;

        lblActionType.Text = "Edit Organization";
        if (tn.Parent == null)
            ddlOrgParent.SelectedIndex = 0;
        else
            ddlOrgParent.SelectedValue = tn.Parent.Value;

        OrganizationCDE org = OrganizationBL.GetOrgByOrgID(Int32.Parse(tn.Value));
        txtOrgID.Text = org.OrgID.ToString();
        txtOrgName.Text = org.OrgName;
        if (org.ChildCount == 0)
            btnDelete.Visible = true;
    }

    private void Load_OrgsParentDDL()
    {
        if (ddlOrgParent.Items.Count == 1)
        {
            ddlOrgParent.DataSource = OrganizationBL.dsLoadDataSet("SPM_spGetParentOrgs");
            ddlOrgParent.DataBind();
        }
    }
    protected void SubmitClick(Object source, EventArgs e)
    {
        if (Page.IsValid)
        {
            try
            {
                int intOrgID = 0;
                bool blOrgID = Int32.TryParse(txtOrgID.Text.ToString(), out intOrgID);

                OrganizationBL.UpdateOrgByOrgID(intOrgID, txtOrgName.Text, Int32.Parse(ddlOrgParent.SelectedValue), Session["loginname"].ToString());
                Response.Redirect("~/Admin/Organization.aspx");
            }
            catch (Exception ex)
            {
                string strErrorType = ex.Message.ToString().Substring(0, 8);

                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                if (!Request.IsLocal && strErrorType != "APMError")
                {
                    Server.ClearError();
                    Server.Transfer("~/Errors/GenericErrorPage.htm");
                }
            }
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            // Loop through all validation controls to see which
            // generated the errors
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }
    protected void DeleteClick(object source, EventArgs e)
    {
        OrganizationBL.DeleteOrgByOrgID(Int32.Parse(txtOrgID.Text));
        Response.Redirect("~/Admin/Organization.aspx");
    }
}
